package org.grow.secure.service;

import com.querydsl.jpa.impl.JPAQueryFactory;
import org.grow.secure.dao.UserInfoDao;
import org.grow.secure.entity.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author: xwg
 * @CreateDate: 21-7-15
 */

@Service
public class UserInfoService implements UserDetailsService {

    @Autowired
    private UserInfoDao userInfoDao;
    @Autowired
    private JPAQueryFactory jpaQueryFactory;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        UserInfo userInfo = userInfoDao.findByUsername(s);
        if (userInfo==null) throw new UsernameNotFoundException("用户名不存在");


//        String username = "libai06";
        QUserInfo u = QUserInfo.userInfo;
        QUserRole ur = QUserRole.userRole;
        QRoleInfo r = QRoleInfo.roleInfo;
        List<RoleInfo> roleInfos = jpaQueryFactory.select(r)
                .from(u)
                .innerJoin(ur).on(u.userId.eq(ur.userFk))
                .innerJoin(r).on(ur.roleFk.eq(r.roleId))
                .where(u.username.eq(s))
                .fetch();
        userInfo.setAuthorities(roleInfos);

        System.out.println("身份认证：数据库查询到的："+userInfo);
        return userInfo;
    }
}
